using System;
using System.Collections;
using System.Security.Principal;
using System.Web;
using System.Reflection;
using System.Data;

using Castle.Facilities.NHibernateIntegration;
using Castle.Services.Transaction;
using NHibernate;
using NetBpm.Util.Client;
using NetBpm.Workflow.Organisation.EComp;
using NetBpm.Workflow.Organisation;
using NetBpm.Workflow.Delegation;
using NetBpm.Workflow.Definition;
using NetBpm.Workflow.Definition.EComp;
using NetBpm.Workflow.Execution;
using NetBpm.Workflow.Execution.EComp;
using NetBpm.Workflow.Definition.Attr;
using NetBpm.Workflow.Log.EComp;

using BEGDC.Utility.ExceptionManagement;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.BL.Common;
using BEGDC.Utility.Castle;
using BEGDC.CC.Entity;

namespace BEGDC.CC.BL.CCFlow.ESC
{
	/// <summary>
	/// Summary description for CRFlow.
	/// </summary>
	public class ESCFlow : FlowBase
	{
		public ESCFlow()
		{
		}

		protected override string ProjectType
		{
			get
			{
				return WorkflowTypes.ESC;
			}
		}

		public long StartCOFlow()
		{
			IExecutionSessionLocal executionComponent = null;
			try
			{
				long processDefinitionID = BEGDC.CC.BL.Workflow.Configuration.GetProcessDefinitionID(WorkflowTypes.CO);
				executionComponent = ServiceLocator.Instance.GetService(typeof (IExecutionSessionLocal)) as IExecutionSessionLocal;
				IProcessInstance processInstance = executionComponent.StartProcessInstance(processDefinitionID);
				return processInstance.RootFlow.Id;
			}
			catch(Exception ex)
			{
				CCS.Utility.LogAccess.WriteErrLog( ex.StackTrace, ex.Message );
				throw new Exception("Start CO Process error.", ex);
			}
			finally
			{
				ServiceLocator.Instance.Release(executionComponent);
			}
		}

		public void InitializeCOProjectMember(ISession session, int appId)
		{
			try
			{
				IUtility utiService = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
				int typeId = utiService.GetDicItemID(BEGDC.CC.BL.Workflow.WorkflowTypes.CO, BEGDC.CC.BL.Common.DicType.Application_Type);
				string query = "select * from AssignmentDefination where ProjectType = "+typeId.ToString();
				DataTable table = BEGDC.Utility.NHibernate.NHibernateUtil.Execute(session, query);

				for(int i=0; i<table.Rows.Count; i++)
				{
					FlowMember fm = new FlowMember();
					fm.Application = new Application();
					fm.Application.Id = appId;
					fm.Role = new Role();
					fm.Role.Id = Convert.ToInt32(table.Rows[i]["RoleId"]);
					fm.Step = new Step();
					fm.Step.Id = Convert.ToInt32(table.Rows[i]["StepId"]);
					session.Save(fm);
				}
			}
			catch(Exception ex)
			{
				CCS.Utility.LogAccess.WriteErrLog( ex.StackTrace, ex.Message );
				throw ex;
			}
			finally
			{
			}
		}
	}
}
